package com.yfp.client.controller;

import com.alibaba.fastjson2.JSONObject;
import com.yfp.client.annotation.AnonymousAccess;
import com.yfp.client.domain.ClientCoupon;
import com.yfp.client.domain.MarActivity;
import com.yfp.client.domain.MarCoupon;
import com.yfp.client.domain.MarCouponExport;
import com.yfp.client.domain.dto.ActiviryAcquireDTO;
import com.yfp.client.domain.dto.OrderCreateDTO;
import com.yfp.client.domain.vo.ClientCouponOrderVO;
import com.yfp.client.domain.vo.CouponPackVO;
import com.yfp.client.domain.vo.PopupVO;
import com.yfp.client.enums.ClientCouponStatusEnums;
import com.yfp.client.service.ClientCouponService;
import com.yfp.client.service.MarCouponExportService;
import com.yfp.client.service.MarCouponPackService;
import com.yfp.client.service.MarCouponService;
import com.yfp.client.util.RedisKey;
import com.yfp.client.util.Response;
import com.yfp.client.util.ResponseEnum;
import com.yfp.client.util.SecurityUtils;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.web.controller.BaseController;
import com.yfp.common.core.web.page.TableDataInfo;
import com.yfp.common.redis.service.RedisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 *
 * @CreateDate: 2024/7/16 19:01
 * @UpdateUser:
 * @UpdateDate: 2024/7/16 19:01
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
@RestController
@RequestMapping("/client/coupon")
@Tag(name = "客户优惠券")
@Slf4j
public class ClientCouponController extends BaseController {
    @Autowired
    private ClientCouponService clientCouponService;
    @Autowired
    private MarCouponService marCouponService;
    @Autowired
    private MarCouponExportService marCouponExportService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MarCouponPackService marCouponPackService;

    @Operation(summary = "活动发券")
    @GetMapping("/popup")
    public Response<PopupVO> popup(String cityName) {
        PopupVO popup = clientCouponService.popup(SecurityUtils.getClientId(), cityName);
        return Response.success(popup);
    }

    @Operation(summary = "领券中心-列表")
    @GetMapping("/list")
    public Response<TableDataInfo<List<MarCoupon>>> list(String cityName) {
        startPage();
        String clientId = SecurityUtils.getClientId();
        List<MarCoupon> marCoupons = marCouponService.validList(clientId, cityName);
        // 正常券
        List<ClientCoupon> clientCoupons = clientCouponService.findCouponCentre(ClientCouponStatusEnums.NORMAL.getCode(), clientId);
        // 待开始券
        List<ClientCoupon> clientCoupons2 = clientCouponService.findCouponCentre(ClientCouponStatusEnums.NOT_STARTED.getCode(), clientId);
        clientCoupons.addAll(clientCoupons2);
        MarCoupon marCoupon = null;
        for (ClientCoupon clientCoupon : clientCoupons) {
            marCoupon = new MarCoupon();
            BeanUtils.copyProperties(clientCoupon, marCoupon);
            marCoupons.add(marCoupon);
        }
        return Response.success(getDataTable(marCoupons));
    }

    @Operation(summary = "领券中心-领取券")
    @PostMapping("/acquire/{couponId}")
    public Response<ResponseEnum> acquire(@PathVariable("couponId") Long couponId, String cityName) {
        return Response.result(clientCouponService.acquire(couponId, SecurityUtils.getClientId(), cityName));
    }

    @Operation(summary = "活动-领取券")
    @PostMapping("/activiryAcquire")
    public Response<ResponseEnum> activiryAcquire(@RequestBody ActiviryAcquireDTO activiryAcquireDTO) {
        activiryAcquireDTO.setClientId(SecurityUtils.getClientId());
        return Response.result(clientCouponService.activiryAcquire(activiryAcquireDTO));
    }

    @AnonymousAccess
    @Operation(summary = "邀请有礼活动-详情")
    @PostMapping("/activity/info")
    public Response<MarActivity> activity(@RequestBody ActiviryAcquireDTO activiryAcquireDTO) {
        MarActivity activity = clientCouponService.activity(activiryAcquireDTO);
        return Response.success(activity);
    }

    @Operation(summary = "查询礼包")
    @GetMapping("/findCouponPack")
    public Response<CouponPackVO> findCouponPack(Long couponPackId) {
        CouponPackVO couponPackVO = clientCouponService.findCouponPack(couponPackId);
        return Response.success(couponPackVO);
    }

    @Operation(summary = "领取礼包")
    @PostMapping("/couponPack/{marketingId}")
    public Response<ResponseEnum> couponPack(@PathVariable("marketingId") Long marketingId,@RequestBody ActiviryAcquireDTO activiryAcquireDTO) {
        boolean result = clientCouponService.acquireCouponPack(marketingId, SecurityUtils.getClientId(), activiryAcquireDTO.getCityName(), null);
        if (result){
            return Response.success();
        } else {
            return Response.result(ResponseEnum.NOT_COUPON_PACK);
        }
    }

    @Operation(summary = "我的优惠券")
    @GetMapping("/clientCoupons")
    public Response<TableDataInfo<List<ClientCoupon>>> list(@Param("status") Integer status) {
        startPage();
        List<ClientCoupon> clientCoupons = clientCouponService.findListByStatusAndClientId(status, SecurityUtils.getClientId());
        return Response.success(getDataTable(clientCoupons));
    }

    @Operation(summary = "可用营业点")
    @GetMapping("/getOutlets")
    public Response getOutlets(Long couponId) {
        return Response.success(marCouponService.getOutlets(couponId));
    }

    @PostMapping("/order/detail/list")
    @Operation(summary = "订单详情-优惠券列表", description = "订单详情-优惠券列表。下单选择优惠券，展示用户所有的优惠券列表包含可使用、不可使用")
    public R<ClientCouponOrderVO> getClientCouponOrderList(@RequestBody OrderCreateDTO orderCreateDTO) {
        return R.ok(clientCouponService.getClientCouponOrderList(orderCreateDTO));
    }

    @Operation(summary = "核销券")
    @PostMapping("/verification/{marCouponExportId}")
    public Response<ResponseEnum> verification(@PathVariable("marCouponExportId") String marCouponExportId) {
        MarCouponExport marCouponExport = marCouponExportService.findById(marCouponExportId);
        if (null == marCouponExport) {
            return Response.result(ResponseEnum.COUPON_NOT_EXIST);
        } else if (marCouponExport.getStatus() == 1) {
            return Response.result(ResponseEnum.COUPON_NOT_COUNT);
        } else if (marCouponExport.getStatus() == 2) {
            return Response.result(ResponseEnum.COUPON_LOSE_EFFICACY);
        }
        ResponseEnum responseEnum = clientCouponService.verification(marCouponExport.getMarCouponId(), SecurityUtils.getClientId());
        if (responseEnum.getCode() == ResponseEnum.OPERATOR_SUCCESS.getCode()) {
            Long clientCouponId = redisService.getCacheObject(MessageFormat.format(RedisKey.CLIENTCOUPON, SecurityUtils.getClientId()));
            log.info("核销券cacheObject：{}", clientCouponId);
            marCouponExport.setClientCouponId(clientCouponId);
            marCouponExport.setStatus(1);
            marCouponExport.setReceiveTime(new Date());
            log.info("marCouponExport：{}", JSONObject.toJSONString(marCouponExport));
            marCouponExportService.editStatusById(marCouponExport);

            redisService.deleteObject(MessageFormat.format(RedisKey.CLIENTCOUPON, SecurityUtils.getClientId()));
        }
        return Response.result(responseEnum);
    }

    @GetMapping("/countdown")
    @Operation(summary = "首页-优惠券倒计时", description = "首页-优惠券倒计时")
    public R<ClientCoupon> getClientCouponCountdown() {
        return R.ok(clientCouponService.getClientCouponCountdown());
    }

    @GetMapping("/list/newIcon")
    @Operation(summary = "首页-领券中心-上新图标", description = "首页-领券中心-上新图标[true:有上新图标，false:无上新图标]")
    public R<Boolean> listNewIcon(String cityName) {
        return R.ok(clientCouponService.listNewIcon(cityName));
    }
}